import Vue from 'vue'
import VueRouter from 'vue-router'
import { Dialog } from 'vant';
import store from '@/store/'

Vue.use(VueRouter)

const routes = [{
        path: '/login',
        name: 'login',
        component: () =>
            import ('@/views/login/'),
        meta: { requiresAuth: false } // 添加额外的自定义数据
    },
    {
        path: '/',
        // name: 'layout',
        component: () =>
            import ('@/views/layout/'),
        children: [{
                path: '', // 默认子路由
                name: 'home',
                component: () =>
                    import ('@/views/home/'),
                meta: { requiresAuth: false }
            },
            {
                path: '/qa',
                name: 'qa',
                component: () =>
                    import ('@/views/qa/'),
                meta: { requiresAuth: true }
            },
            {
                path: '/vi',
                name: 'vi',
                component: () =>
                    import ('@/views/video/'),
                meta: { requiresAuth: false }
            },
            {
                path: '/my',
                name: 'my',
                component: () =>
                    import ('@/views/my/'),
                meta: { requiresAuth: false }
            }
        ]
    },
    {
        path: '/search',
        name: 'name',
        component: () =>
            import ('@/views/search/'),
        meta: { requiresAuth: false }
    },
    {
        path: '/article/:articleId',
        name: 'article',
        component: () =>
            import ('@/views/article/'),
        meta: { requiresAuth: true },
        // 将动态路由参数映射到组件的 props 中，无论是访问还是维护性都很方便
        props: true
    },
    {
        path: '/userprofile',
        name: 'userprofile',
        component: () =>
            import ('@/views/user-profile'),
        meta: { requiresAuth: true }
    },
    {
        path: '/userchat',
        name: 'userchat',
        component: () =>
            import ('@/views/user-chat'),
        meta: { requiresAuth: true }
    },
]

const router = new VueRouter({
    routes
})

// to: 要访问的页面右路信息
// from: 来自哪个页面的路由信息
// next: 放行的标记
router.beforeEach((to, from, next) => {
    // 校验登录状态，提示用户
    if (to.meta.requiresAuth) {
        // 如果已经登录了，就跳过
        if (store.state.user) {
            return next()
        }

        Dialog.confirm({
            title: '访问提示',
            message: '该功能需要登录才能进行访问，确认登录吗？',
        }).then(() => {
            // 确认执行这里
            router.replace({
                name: 'login',
                query: {
                    redirect: router.currentRoute.fullPath
                }
            })
        }).catch(() => {
            // 取消执行这里
            next(false)
        });
    } else {
        // 不需要登录状态的页面，直接过去
        next()
    }
})

export default router